package com.yy.wga.pay.service.third;

import com.yy.wga.common.core.dto.Result;
import com.yy.wga.common.util.common.JsonUtils;
import com.yy.wga.common.util.common.StringUtils;
import com.yy.wga.pay.feign.api.AliPayNotifyFeign;
import com.yy.wga.pay.feign.eunms.EPayStatus;
import com.yy.wga.pay.feign.request.third.AliPayPayNotifyRequest;
import com.yy.wga.pay.service.client.AliPayClient;
import com.yy.wga.pay.service.manager.PayCallbackManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝通知接口
 *
 * @author guochao
 * @date 2021/6/5 17:00
 */
@Slf4j
@RestController
@RequestMapping("/api/pay/third/aliPay")
public class AliPayNotifyController implements AliPayNotifyFeign {

    private final PayCallbackManagerService payCallbackManagerService;
    private final AliPayClient aliPayClient;

    public AliPayNotifyController(PayCallbackManagerService payCallbackManagerService, AliPayClient aliPayClient) {
        this.payCallbackManagerService = payCallbackManagerService;
        this.aliPayClient = aliPayClient;
    }

    /**
     * 异步通知
     * @param appId
     * @param params
     * @return
     */
    @PostMapping(value = "/pay/notify/{appId}")
    public Result<String> payNotify(@PathVariable(name = "appId", required = false) String appId, Map<String,String> params)  {
        if (StringUtils.isBlank(appId)) {
            appId = "2021003158693376";
        }
        // 参数校验
        if (!aliPayClient.rsaCheckV1(params, appId)) {
            return Result.fail("FAILURE");
        }
        log.info("支付宝支付回调参数:{}", params);
        String json = JsonUtils.toJSONString(params);
        AliPayPayNotifyRequest aliPayPayNotifyRequest = JsonUtils.parseObject(json, AliPayPayNotifyRequest.class);
        // 封装统一回调处理实体
        AppPayNotifyDTO appPayNotifyDTO = new AppPayNotifyDTO();
        appPayNotifyDTO.setOutTradeNo(aliPayPayNotifyRequest.getOutTradeNo());
        appPayNotifyDTO.setSuccessTime(aliPayPayNotifyRequest.getGmtClose());
        EPayStatus wechatTradeState = aliPayPayNotifyRequest.getTradeStatus().getPayStatus();
        if (wechatTradeState == null) {
            log.error("返回未知的订单状态:{}", JsonUtils.toJSONString(aliPayPayNotifyRequest));
        } else {
            appPayNotifyDTO.setTradeState(wechatTradeState);
            appPayNotifyDTO.setTransactionId(aliPayPayNotifyRequest.getTradeNo());
            payCallbackManagerService.payNotify(appPayNotifyDTO);
        }
        return Result.success("SUCCESS");
    }
}
